<script>
/* 关系数据源 */

import RelationDataAdd from './RelationDataAdd';
import * as utils from '@/utils/helps';

export default {
  name: 'RelationData',
  components: {
    RelationDataAdd,
  },
  data() {
    return {
      relationColumns: [
        {
          title: 'NO.',
          key: 'num',
          width: 100,
        },
        {
          title: '名称',
          key: 'name',
          render: (h, params) => <strong>{params.row.name}</strong>,
        },
        {
          title: '类型',
          key: 'type',
        },
        {
          title: '修改时间',
          key: 'updatetime',
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          align: 'center',
          render: (h, params) => {
            return (
              <div>
                <a style={{ marginRight: '5px' }} onClick={() => this.modify(params.row.name)}>
                  修改
                </a>
                <a onClick={() => this.delete(params.row.name)}>删除</a>
              </div>
            );
          },
        },
      ],
      relationData: [],
      isDisable: false, // 传递给子组件的值
      formItem: {}, //传递给子组件的值
      formOldItem: {}, // copy值
      dialog: false, // 判断弹出框的显示/隐藏
      isEmpty: false, //判断表单内容是否全部填完整
      isTheSame: false, //修改连接数据是否相同
      isNewForm: true, //判断弹出框状态是新建还是编辑
      modelTitle: '新建连接', //储存弹出框title
      test_loading: false, // button等待状态
      modal_loading: false, // button等待状态
      pageNum: 1, //数据总条数
    };
  },
  watch: {
    // 表单验证
    formItem: {
      handler(newVal) {
        this.isTheSame = true;
        this.isEmpty = false;
        if (this.isNewForm) {
          this.modelTitle = '新建连接';
          this.isDisable = false;
        } else {
          this.modelTitle = '修改连接';
          this.isDisable = true;
        }
        for (let prop in newVal) {
          if (!this.isNewForm) {
            continue;
          }
          let isString = typeof newVal[prop] == 'string';
          newVal[prop] = isString ? newVal[prop].replace(/(^\s*)|(\s*$)/g, '') : newVal[prop]; //如果是字符串则去掉前后空格
          if (isString ? newVal[prop] == '' : false) {
            this.isEmpty = true;
          }
          if (!this.isNewForm && newVal[prop] != this.formOldItem[prop]) {
            this.isTheSame = false; //修改连接数据是否相同
          }
        }
      },
      deep: true,
    },
  },
  mounted() {
    this.loadDsList();
  },
  methods: {
    // 查询连接的数据库
    async loadDsList() {
      this.relationData = [];
      this.totalRelationData = [];
      let num = 1;
      const response = await api.ETL.findDbList();
      response.data.forEach(item => {
        this.totalRelationData.push({
          num: num,
          name: item.name,
          type: '关系数据库',
          updatetime: '',
        });
        num++;
      });
      this.relationData = utils.computedPageData(this.totalRelationData, 1);
      this.pageNum = num;
    },
    // 新建连接
    addRelativeData() {
      this.dialog = true;
      this.formItem = {
        MSSQLUseIntegratedSecurity: false,
        access: 0,
        databaseName: '',
        extraOptions: [],
        hostname: '',
        lowerCaseIdentifiersCheck: false,
        name: '',
        password: '',
        port: '',
        quoteIdentifiersCheck: false,
        streamingResults: true,
        supportBooleanDataType: true,
        type: 'POSTGRESQL',
        upperCaseIdentifiersCheck: false,
        username: '',
      };
    },
    // 修改
    async modify(name) {
      this.dialog = true;
      const response = await api.ETL.findDbInfo({
        dbname: name,
      });
      this.formItem = response.data;
      this.isNewForm = false;
      this.formOldItem = JSON.parse(JSON.stringify(response.data));
    },
    // 删除
    delete(name) {
      this.$Modal.confirm({
        title: `警告`,
        content: '此操作不可恢复，确定执行删除操作？',
        onOk: async () => {
          const response = await api.ETL.deleteDB({
            dbname: name,
          });
          this.$Message.info(response.data);
          this.loadDsList();
        },
      });
    },
    // 测试连接
    async connectTest() {
      this.test_loading = true;
      const response = await api.ETL.testDb(this.formItem);
      this.$Message.info(response.data.message);
      this.test_loading = false;
    },
    // 创建连接
    async createConnect() {
      if (this.isTheSame && !this.isNewForm) {
        this.dialog = false;
        return;
      }
      this.modal_loading = true;
      const response = await api.ETL.addDb(this.formItem);
      this.modal_loading = false;
      this.$Message.success('创建成功！');
      this.dialog = false;
      this.isNewForm = true;
      this.loadDsList();
    },
    changePage(index) {
      this.relationData = [];
      this.relationData = utils.computedPageData(this.totalRelationData, index);
    },
  },
};
</script>

<template>
  <div>
    <div>
      <Button
        type="primary"
        icon="plus"
        @click="addRelativeData"
      >新建</Button>
    </div>
    <Table
      :columns="relationColumns"
      :data="relationData"
      size="small"
      stripe
    />
    <Page
      :total="pageNum"
      :current="1"
      size="small"
      @on-change="changePage"
    />
    <Modal
      v-model="dialog"
      :title="modelTitle"
      @on-cancel="isNewForm=true"
    >
      <RelationDataAdd
        ref="nForm"
        :form-item="formItem"
        :is-disable="isDisable"
      />
      <div slot="footer">
        <Button
          :loading="test_loading"
          :disabled="isEmpty"
          type="ghost"
          @click="connectTest"
        >测试连接</Button>
        <Button
          :loading="modal_loading"
          :disabled="isEmpty"
          type="primary"
          @click="createConnect"
        >确定</Button>
      </div>
    </Modal>
  </div>
</template>


<style lang="less" scoped>
.k-table-wrapper {
  margin: 10px 0;
}

.k-modal {
  top: 20px;
  width: 500px;
}

.k-page {
  float: right;
  margin-top: 5px;
}
</style>
